<template>
  <div class="contract-materials">
    <div class="contract-materials-content">
      <div class="contract-materials-list" v-for="goods in orderDataList" :key="goods.contractId">
        <div class="contract-materials-list__header">
          <div class="flex justify-between align-center">
            <div class="divider-blue"></div>
            <div class="contract-number">合同编号：{{ goods.contractNo }}</div>
            <el-tag v-show="goods.status === 0" type="warning">待生成</el-tag>
            <el-tag v-show="goods.status === 2" class="ml-2" color="#D9EDFF">签约中</el-tag>
            <el-tag v-show="goods.status === 3" class="ml-2" color="#D9EDFF">执行中</el-tag>
            <el-tag v-show="goods.status === 1" class="ml-2" color="#D9EDFF">审批中</el-tag>
            <el-tag v-show="goods.status === 4" class="ml-2" type="info">已作废</el-tag>
            <div style="margin-left: 30px" v-if="goods.signingTime">签约时间：{{ goods.signingTime }}</div>
          </div>
          <div class="flex justify-between align-center contract-materials-buttons">
            <div v-for="(item, i) in getVisibleButtons(goods)" :key="item.text" class="flex justify-between align-center">
              <div @click="item.action">{{ item.text }}</div>
              <div class="divider-grey" v-if="i < getVisibleButtons(goods).length - 1"></div>
            </div>
          </div>
        </div>
        <el-divider />
        <div style="margin-bottom: 20px" class="flex space-between align-center">
          <div>
            <div class="label-name mb20">
              合同名称：<span>{{ goods.title }}</span>
            </div>
            <div class="label-name">
              合同预算报价单：<span>{{ goods.budgetName }}</span>
            </div>
          </div>
          <div>
            <div class="label-name mb20">
              合同类型&形式：<span>{{ goods.contractType + "-" + signingList[goods.signingMethod] }}</span>
            </div>
            <div class="label-name">
              合同总金额（元）：<span style="color: red">{{ goods.totalAmount }}</span>
            </div>
          </div>
          <div>
            <div class="label-name mb20">
              签约公司：<span>{{ goods.signCompany }}</span>
            </div>
            <div class="label-name">
              售后单：<span style="color: #007dff; cursor: pointer" @click="handleTbasTo(goods)">{{
                goods.afterSalesNumber
              }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <custom-pagination
      v-if="orderDataList.length > 0"
      :background="false"
      :total="listTotal"
      v-model:limit="tableParams.size"
      v-model:page="tableParams.current"
      layout="total, sizes, prev, pager, next, jumper"
      @pagination="handelPage"
    >
    </custom-pagination>
    <!-- 查看合同   -->
    <file-preview ref="roleRef" />
    <!-- 上传签约合同 -->
    <el-dialog
      v-model="pdfDialogVisible"
      title="上传合同"
      width="475px"
      style="margin-top: 150px !important; border-radius: 10px"
      center
    >
      <pdf-upload
        v-if="pdfDialogVisible"
        :fileList="logoImageList"
        :accept="'.pdf,.jpg,.jpeg,.png'"
        multiple
        :max-size="20"
        :max-length="50"
        @upload-success="uploadLogoImageList"
        @upload-remove="uploadImageListRemove"
      />
      <template #footer>
        <div class="upload-but" style="text-align: center">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="postUpload" :disabled="logoImageList.length <= 0">确认上传</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 作废弹窗   -->
    <div class="delete-dialog">
      <el-dialog :show-close="false" v-model="centerDialogVisible" :title="title + '-' + contractNo" width="306px" center>
        <span>你确定要作废此合同吗？作废后合同信息及合同文件均被删除。</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleDelete">删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 查看签约合同   -->
    <div>
      <el-dialog
        v-model="imgVisible"
        title="查看签约合同"
        width="455px"
        style="margin-top: 150px !important; border-radius: 10px"
        center
      >
        <div>
          <div class="upload-file-li" v-if="fileListData.length > 0">
            <div v-for="item in fileListData" :key="item" class="upload-file-item">
              <el-image style="width: 24px; height: 24px" :src="item.fileUrl" :fit="fit" :preview-src-list="[item.fileUrl]">
                <template #error>
                  <div class="image-slot">
                    <img
                      @click="handlePdf(item.fileUrl)"
                      style="width: 24px; height: 24px; cursor: pointer"
                      src="@/assets/images/errpdf.png"
                      alt=""
                    />
                  </div>
                </template>
              </el-image>
              <div class="flile-name">{{ item.name || item.fileName }}</div>
            </div>
          </div>
          <el-empty v-else description="暂无数据" image-size="50" />
        </div>
      </el-dialog>
    </div>
    <!-- 电子签约   -->
    <div>
      <el-dialog
        v-model="electronicVisible"
        title="合同电子签约"
        width="485px"
        style="margin-top: 150px !important; border-radius: 10px"
        center
      >
        <el-form label-position="top" label-width="100px" :model="formLabelAlign" style="max-width: 460px">
          <el-form-item label="客户姓名">
            <el-input v-model="formLabelAlign.customerName" disabled />
          </el-form-item>
          <el-form-item label="客户身份证号">
            <el-input v-model="formLabelAlign.customerIdCard" disabled />
          </el-form-item>
          <el-form-item label="客户手机号">
            <el-input v-model="formLabelAlign.customerMobileCode" disabled />
          </el-form-item>
          <el-form-item label="客户地址">
            <el-input v-model="formLabelAlign.customerAddress" disabled />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="upload-but" style="text-align: center">
            <div v-if="signUrl === ''">
              <el-button @click="electronicVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit" :loading="subLoading">发起签约</el-button>
            </div>
            <el-button v-else class="copy" type="primary" @click="handleCopyUrl">复制客户签约地址</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 发起整改增减项   -->
    <div class="delete-dialog">
      <el-dialog :show-close="false" v-model="visible" :title="rectificationTitle" width="400px" center>
        <div class="flex align-center">
          <div style="margin-right: 40px"><span style="color: red">*</span>是否创建报价变更单</div>
          <el-radio-group v-model="radio" class="ml-4">
            <el-radio :label="1" size="large">是</el-radio>
            <el-radio :label="2" size="large">否</el-radio>
          </el-radio-group>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="handleGotoAdd">下一步</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { manageList } from "@/apis/clientManager";
import { checkReform, contractFileDown, deleteManage, imgDetail, initiate, uploadFile } from "@/apis/template/index.js";
import { useRoute, useRouter } from "vue-router";
import { downloadPDF, handelCopy } from "@/utils";
import { microAppMainRouter } from "@/microApp";

const radio = ref(2);
const subLoading = ref(false);
const signUrl = ref(""); // 签约地址
const electronicVisible = ref(false); // 电子签约
const visible = ref(false); // 发起整改增减项
const rectificationTitle = ref(""); // 发起整改增减项
const signingList = ref(["", "纸质", "电子", "电子或纸质"]);
const route = useRoute();
const router = useRouter();
const listTotal = ref(0);
const fileListData = ref([]);
const orderDataList = ref([]);
const contractId = ref(); // 合同ID
const contractNo = ref(); // 合同编号
const customerId = ref(); // 客户id
const budgetId = ref(); //报价单id
const roleRef = ref();
const title = ref("");
const logoImageList = ref([]);
const imgVisible = ref(false);
const pdfDialogVisible = ref(false);
const centerDialogVisible = ref(false);
const tableParams = reactive({
  current: 1,
  size: 10,
  customerId: route.query.customerId
});
const formLabelAlign = ref({
  title: "",
  customerAddress: ""
});
const emits = defineEmits(["setActive"]);
//定义按钮
const getVisibleButtons = goods => {
  const buttons = [
    {
      condition: () => !!goods.fileUrl,
      text: "查看",
      action: () => handelClickDetail(goods)
    },
    {
      condition: () => goods.isReform,
      text: "发起整改",
      action: () => handleAdd(goods, 1)
    },
    {
      condition: () => goods.isChange,
      text: "发起增减项",
      action: () => handleAdd(goods, 3)
    },
    {
      condition: () => goods.status === 0 || goods.status === 2,
      text: "生成合同文件",
      action: () => handleGoto(goods)
    },
    {
      condition: () => goods.signingMethod === 2 && goods.status === 2,
      text: "电子签约",
      action: () => handleSubmitSign(goods)
    },
    {
      condition: () => (goods.status === 2 || goods.status === 3) && goods.signingMethod === 1,
      text: "上传签约合同",
      action: () => handleUpload(goods)
    },
    {
      condition: () => goods.status === 3,
      text: "查看签约合同",
      action: () => getFileDetail(goods)
    },
    {
      condition: () => goods.status === 3,
      text: "下载签约合同",
      action: () => handleDownFile(goods)
    },
    {
      condition: () => goods.status === 1 || goods.status === 2 || goods.status === 3,
      text: "下载生成合同",
      action: () => handleDown(goods)
    },
    {
      condition: () => goods.status === 0 || goods.status === 2,
      text: "作废",
      action: () => handelCancellation(goods)
    }
  ];
  // 过滤可见按钮
  return buttons.filter(btn => btn.condition());
};
// 获取列表数据
const getPageList = async () => {
  const { data } = await manageList(tableParams);
  listTotal.value = data.total;
  orderDataList.value = data.records;
  console.log(data);
};
// 删除上传
const uploadImageListRemove = index => {
  logoImageList.value.splice(index, 1);
};
// 关闭上传
const handleClose = () => {
  logoImageList.value = [];
  pdfDialogVisible.value = false;
};
const postUpload = async () => {
  await uploadFile({
    contractId: contractId.value,
    urlList: logoImageList.value
  });
  logoImageList.value = [];
  pdfDialogVisible.value = false;
  await getPageList();
  ElMessage.success("上传成功");
};
const handleDown = row => {
  let name = row.title + "-" + row.contractNo + ".pdf";
  downloadPDF(row.fileUrl, name);
};
const handelPage = () => {
  orderDataList.value = [];
  getPageList();
};
const handleSubmitSign = row => {
  signUrl.value = "";
  contractNo.value = row.contractNo;
  formLabelAlign.value = { ...row };
  electronicVisible.value = true;
};
// 发起电子签约
const handleSubmit = async () => {
  subLoading.value = true;
  try {
    const { data } = await initiate({ contractNo: contractNo.value });
    if (data.signUrl) {
      signUrl.value = data.signUrl;
      ElMessage.success("发起成功，请复制客户签约地址签约");
    } else {
      electronicVisible.value = false;
      await getPageList();
    }
    subLoading.value = false;
  } catch (e) {
    subLoading.value = false;
  }
};
// 复制签约地址
const handleCopyUrl = () => {
  handelCopy(signUrl.value);
};

/*查看操作*/
const handelClickDetail = row => {
  roleRef.value.contractId = row.contractId;
  roleRef.value.open(row.contractId);
};
const uploadLogoImageList = data => {
  logoImageList.value.push({
    ...data
  });
};
// 获取签约文件
const getFileDetail = async row => {
  const { data } = await imgDetail(row.contractId);
  fileListData.value = data;
  imgVisible.value = true;
};

const handleDownFile = row => {
  contractFileDown(row.contractId).then(res => {
    console.log(res, 9999);
    if (res.data) {
      window.open(res.data);
    }
  });
};

/*上传pdf*/
const handleUpload = row => {
  contractId.value = row.contractId;
  logoImageList.value = [];
  pdfDialogVisible.value = true;
};
/* 作废 */
const handelCancellation = row => {
  contractId.value = row.contractId;
  contractNo.value = row.contractNo;
  title.value = row.title;
  centerDialogVisible.value = true;
};
// 作废合同
const handleDelete = async () => {
  const { code } = await deleteManage({ contractId: contractId.value });
  if (code === 200) {
    getPageList();
    centerDialogVisible.value = false;
  }
};
const handleGoto = row => {
  microAppMainRouter("push", {
    path: "/sales-contract/contracts-provided",
    query: {
      contractId: row.contractId,
      title: row.title,
      customerId: route.query.customerId
    }
  });
};
// 跳转到售后清单
const handleTbasTo = () => {
  emits("setActive", { key: "rectification" });
};
const handleAdd = async (row, type) => {
  budgetId.value = row.budgetId;
  customerId.value = row.customerId;
  contractId.value = row.contractId;
  rectificationTitle.value = type === 1 ? "创建整改售后单" : "创建增减项售后单";
  // 发起整改
  if (type === 1) {
    visible.value = true;
  } else {
    await gotoQuitePrice();
  }
};
// 发起整改
const handleGotoAdd = async () => {
  if (radio.value === 2) {
    router.push({
      path: "/after-sales-order",
      query: {
        budgetId: budgetId.value,
        contractId: contractId.value,
        customerId: customerId.value,
        afterSalesType: rectificationTitle.value === "创建整改售后单" ? 1 : 3
      }
    });
  } else {
    await gotoQuitePrice();
  }

  visible.value = false;
};
const gotoQuitePrice = async () => {
  const { data } = await checkReform(contractId.value);
  if (data !== true) {
    ElMessage.error("存在进行中的变更单，无法再次发起！");
    return true;
  }
  const baseRouter = window.microApp.router.getBaseAppRouter();
  const routeUrl = baseRouter.resolve({
    path: "/designer/quote-price/following/change",
    query: {
      budgetId: budgetId.value,
      contractId: contractId.value,
      customerId: customerId.value,
      afterSalesType: rectificationTitle.value === "创建整改售后单" ? 1 : 3
    }
  });
  window.open(routeUrl.href, "_blank");
};
//签约文件查看pdf
const handlePdf = url => {
  roleRef.value.openPdf(url);
};
getPageList();
</script>

<style scoped lang="scss">
@import "index";
</style>
